import React, { forwardRef, useImperativeHandle, useState } from "react";
import { Modal } from "antd";
import { hiprint } from "@/components/hiprint";

interface PreviewModalProps {}

export interface PreviewModalRef {
	show: (template: any, printData: any) => void;
}

const PreviewModal = forwardRef<PreviewModalRef, PreviewModalProps>((_, ref) => {
	const [visible, setVisible] = useState(false);
	const [previewHtml, setPreviewHtml] = useState("");

	useImperativeHandle(ref, () => ({
		show: (template, printData) => {
			const html = template.getHtml(printData);
			setPreviewHtml(html);
			setVisible(true);
		},
	}));

	const handlePrint = () => {
		hiprint.print(previewHtml);
	};

	return (
		<Modal
			title="打印预览"
			width="80%"
			open={visible}
			onCancel={() => setVisible(false)}
			footer={[
				<button key="print" onClick={handlePrint}>
					打印
				</button>,
				<button key="close" onClick={() => setVisible(false)}>
					关闭
				</button>,
			]}
		>
			<div dangerouslySetInnerHTML={{ __html: previewHtml }} />
		</Modal>
	);
});

export default PreviewModal;
